package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.mapper.ZjFactoryMapper;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.utils.RandomUtil;
import com.zb.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 厂商表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2024-02-27
 */
@Service
public class ZjFactoryServiceImpl extends ServiceImpl<ZjFactoryMapper, ZjFactory> implements ZjFactoryService {
    @Resource
    private ZjFactoryMapper factoryMapper;
    @Resource
    private ZjFactoryStrategyService factoryStrategyService;
    @Resource
    private ZjFactoryAccountBalanceService factoryAccountBalanceService;
    @Resource
    private ZjFactoryOrderModuleSettlementService factoryOrderModuleSettlementService;
    @Resource
    private ZjFactoryAccountService factoryAccountService;
    @Resource
    private ZjFactoryEmpService factoryEmpService;
    @Resource
    private ZjFactoryRoleService factoryRoleService;
    @Resource
    private ZjFactoryAccountRoleService factoryAccountRoleService;

    // 新增或修改品牌商家
    @Override
    @Transactional
    public void save(Long custAccId, FactoryVo factoryVo) {
        Assert.isNull(factoryMapper.existByName(custAccId, factoryVo.getId(), factoryVo.getName()), "品牌商家已存在：" + factoryVo.getName());
        ZjFactory factory = new ZjFactory();
        BeanUtil.copyProperties(factoryVo, factory);
        if (null != factory.getId()) {
//            Assert.isTrue(StringUtils.isNotBlank(factoryVo.getOrderIdentifierNo()), "工单标识不能为空");
//            Assert.isTrue(factoryVo.getOrderIdentifierNo().length() >= 2 && factoryVo.getOrderIdentifierNo().length() <= 8, "工单标识字符至少输入2个字符，最多允许输入8个字符");
            // 判断工单标识号是否存在
//            Assert.isNull(factoryMapper.existOrderIdentifierNo(custAccId, factoryVo.getId(), factoryVo.getOrderIdentifierNo()), "工单标识已存在：" + factoryVo.getOrderIdentifierNo());
            factory.setOrderIdentifierNo(null);
            this.updateById(factory);
        } else {
            factory.setId(IdWorker.getId());
            factory.setCustAccId(custAccId);
            factory.setNumberNo(RandomUtil.random10());
            factory.setCode(RandomUtil.random60());
            factory.setAnnexCode(RandomUtil.random10());
            factory.setTown(null == factoryVo.getTown()? "" : factory.getTown());
            factory.setTelephone("");
            factory.setOrderIdentifierNo("");
            this.save(factory);
            factoryAccountBalanceService.saveAccountBalance(factory.getId());
        }
        factoryStrategyService.save(factory.getId(), factoryVo.getStrategy());
        factoryOrderModuleSettlementService.save(factory.getId(), factoryVo.getModuleSettlements(), factoryVo.getDelModuleSettlementIds());
        Long accountId = factoryAccountService.save(factoryVo.getAccountId(), factoryVo.getAccountPhone(), factoryVo.getAccountName());
        factoryEmpService.saveFactoryAdmin(factory.getId(), accountId);
        Long roleId = factoryRoleService.saveFactoryAdmin(factory.getId());
        factoryAccountRoleService.saveFactoryAdmin(factory.getId(), accountId, roleId);
    }

    // 获取品牌商家列表
    @Override
    public List<ZjFactory> getList(Long custAccId, FactoryListSelectVo selectVo) {
        return factoryMapper.getList(custAccId, selectVo);
    }

    // 获取品牌商家列表总记录数
    @Override
    public long getListCount(Long custAccId, FactoryListSelectVo selectVo) {
        return factoryMapper.getListCount(custAccId, selectVo);
    }

    // 获取修改品牌商家前的数据查询
    @Override
    public FactoryVo getBeforeUpdateSelect(Long id) {
        ZjFactory factory = this.getById(id);
        Assert.notNull(factory, "品牌商家参数[ " + id + " ]的数据不存在");
        FactoryVo vo = new FactoryVo();
        BeanUtil.copyProperties(factory, vo);

        ZjFactoryStrategy strategy = factoryStrategyService.getById(id);
        FactoryStrategyVo strategyVo = new FactoryStrategyVo();
        BeanUtil.copyProperties(strategy, strategyVo);
        vo.setStrategy(strategyVo);
        vo.setModuleSettlements(factoryOrderModuleSettlementService.getByFactoryId(id).stream().map(mo -> {
            FactoryOrderModuleSettlementVo settlementVo = new FactoryOrderModuleSettlementVo();
            BeanUtil.copyProperties(mo, settlementVo);
            return settlementVo;
        }).toList());
        QueryWrapper<ZjFactoryEmp> empQueryWrapper = new QueryWrapper<>();
        empQueryWrapper.select("factory_account_id")
                .eq("factory_id", id).eq("is_super_account", true);
        ZjFactoryEmp factoryEmp = factoryEmpService.getOne(empQueryWrapper);
        if (null != factoryEmp) {
            ZjFactoryAccount account = factoryAccountService.getById(factoryEmp.getFactoryAccountId());
            if (null != account) {
                vo.setAccountId(account.getId());
                vo.setAccountPhone(account.getPhone());
                vo.setAccountName(account.getName());
            }
        }
        return vo;
    }

    // 审核品牌商家
    @Override
    @Transactional
    public void checkFactory(Long factoryId, Integer checkType) {
        ZjFactory factory = this.getById(factoryId);
        Assert.notNull(factory, "商家参数[ " + factoryId + " ]的数据不存在");
        ZjFactory updateFactory = new ZjFactory();
        updateFactory.setId(factoryId);
        updateFactory.setStatus(checkType == 1? 2 : 3);
        this.updateById(updateFactory);
        if (checkType == 2) {
            return;
        }
        QueryWrapper<ZjFactoryEmp> empQueryWrapper = new QueryWrapper<>();
        empQueryWrapper.select("factory_account_id")
                .eq("factory_id", factory.getId()).eq("is_super_account", true);
        ZjFactoryEmp factoryEmp = factoryEmpService.getOne(empQueryWrapper);
        Long roleId = factoryRoleService.saveFactoryAdmin(factoryId);
        factoryAccountRoleService.saveFactoryAdmin(factoryId, factoryEmp.getFactoryAccountId(), roleId);
    }

    // 获取品牌商家下拉数据
    @Override
    public Map<String, Object> getFactorySelectPage(Long custAccId, SelectVo selectVo) {
        PageUtil.setSelectPageLimit(selectVo);
        QueryWrapper<ZjFactory> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name")
                .eq("cust_acc_id", custAccId).eq("status", 2)
                .orderByDesc("gmt_update");
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        Page<ZjFactory> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        return PageUtil.pageList(page.getCurrent(), page.getPages(), page.getTotal(), page.getRecords().stream().map(factory -> {
            return new SelectResultVo(factory.getId(), factory.getName());
        }).toList());
    }

    // 根据品牌商家ID获取品牌商家名称
    @Override
    public List<ZjFactory> getNameByIds(List<Long> factoryIds) {
        if (CollectionUtil.isEmpty(factoryIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjFactory> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name")
                .in("id", factoryIds);
        return this.list(wrapper);
    }

    // 根据品牌商家ID获取单号标识
    @Override
    public String getOrderIdentifierNoById(Long id) {
        return factoryMapper.getOrderIdentifierNoById(id);
    }
}
